package com.df.bpm.utils.businessViewerV2.res;

import com.df.bpm.utils.businessViewerV2.Main;
import com.df.common.exception.BusinessException;
import com.df.common.utils.CommonUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public abstract class V_scrollPanel<T> extends JScrollPane implements V_fastTable<T>{

    public static int unit=10;

    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    List<T> model;
    Font iFont;

    public V_scrollPanel() {
        unit= (int) Main.unit;
        iFont=new Font("宋体", Font.PLAIN, unit);
    }

    private void fixColWidth(JTable iTable) {
        List<Integer> newColWidths=colWidthSetting();
        if(newColWidths.size()!=getColNames().size()){
            throw new BusinessException("colWidthSetting_字段数量不一致");
        }
        if(CommonUtils.varIsBlank(newColWidths)){
            iTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        }else{
            iTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            for(int i=0;i<newColWidths.size();i++){
                iTable.getColumnModel().getColumn(i).setPreferredWidth(newColWidths.get(i)*unit);
            }
        }
    }



    static JTable newTable(DefaultTableModel model, Font iFont) {
        JTable iTable = new JTable(model);
        iTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, (int) (unit*1.1)));
        iTable.setFont(iFont);
        iTable.setRowHeight((unit+1));
        return iTable;
    }

    public List<T> getModel(){
        return model;
    }


    public JTable putModel(List<T> list) {
        this.getViewport().removeAll();
        List<String> colNames = getColNames();
        String[] title=colNames.toArray(new String[0]);
        int sequenceCol=colNames.indexOf("序号");
        DefaultTableModel model = new DefaultTableModel(null, title){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;//不允许编辑，留作触发双击或拖拽
            }
        };
        if(CommonUtils.varIsNotBlank(list)) {
            for (T row : list) {
                Object[] oRow=getRowValues(row);
                if(sequenceCol!=-1){//序号列计算序号倒序
                    oRow[sequenceCol]=list.size()-model.getRowCount();
                }
                model.addRow(oRow);
            }
        }else{
            list=new ArrayList<>();
        }
        model.addRow(new Object[colNames.size()]);
        list.add(getEmptyRow());
        JTable iTable=newTable(model, iFont);
        fixColWidth(iTable);
        hideCol(iTable);
        this.getViewport().add(iTable);
        iTable.addMouseListener(mouseAdapter4Table(iTable,list));
        this.model=list;
        return iTable;
    }

}
